package service

import (
	"bytes"
	"github.com/dchest/captcha"
	"log"
	"os"
)

type capthcaService struct {
}

// CreateImage 创建图片验证码
func (this *capthcaService) CreateImage() string {

	captchaId := captcha.New()
	return captchaId
}

// Verify 验证
func (this *capthcaService) VerifyString(captchaId, val string) bool {
	return captcha.VerifyString(captchaId, val)
}

func (this *capthcaService) Verify(captchaId string, digits []byte) bool {
	return captcha.Verify(captchaId, digits)
}

// GetImageByte 获取图片二进制流
func (this *capthcaService) GetImageByte(captchaId string) []byte {
	var content bytes.Buffer
	err := captcha.WriteImage(&content, captchaId,
		captcha.StdWidth, captcha.StdHeight)
	if err != nil {
		log.Println(err)
		return nil
	}
	return content.Bytes()
}

// WriteImageFile 写图片文件
func (this *capthcaService) WriteImageFile(b []byte, file string) {
	f, err := os.OpenFile(file, os.O_CREATE|os.O_RDWR, os.ModePerm)
	defer f.Close()
	if err != nil {
		log.Println(err)
	}
	f.Write(b)
}

var (
	CapthcaService *capthcaService
)

func init() {
	var captchaStore = &captchaStore{}
	captcha.SetCustomStore(captchaStore)
	CapthcaService = &capthcaService{}

}
